package cn.edu.java.thread.原子类;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanDemo {
    private static AtomicBoolean flag = new AtomicBoolean(false);

    public static void main(String[] args) {

        Runnable task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                if (flag.compareAndSet(false, true)) {
                    System.out.println(Thread.currentThread().getName() + " entered the critical section.");
                    // 模拟临界区操作
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " exited the critical section.");
                    flag.set(false);
                } else {
                    System.out.println(Thread.currentThread().getName() + " cannot enter the critical section.");
                }
            }
        };

        new Thread(task).start();
        new Thread(task).start();
    }
}

